/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package estg.dae.projecto.bank.impl;

/**
 *
 * @author mario
 */
public class NibValidator {
    public static String createNib(int bankCode, int agencyCode, long accountNumber){

        if (bankCode > 9999.)
            throw new NumberFormatException("Código de Banco inválido");
        if (agencyCode > 9999)
            throw new NumberFormatException("Código de Agência inválido");
        if (accountNumber > (long)99999999999.0)
            throw new NumberFormatException("Numero de conta inválido");

        StringBuilder nib = new StringBuilder(21);
        nib.append(String.format("%04d", bankCode));
        nib.append(String.format("%04d", agencyCode));
        nib.append(String.format("%011d", accountNumber));
        nib.append(digitControlNib(nib.toString()));
        return nib.toString();
    }

    public static boolean validateNib(String nib){
        String digit = digitControlNib(nib);
        char []array = nib.toCharArray();
        String newNib = Character.toString(array[19])+ Character.toString(array[20]) ;
        if (newNib.contains(digit) )
            return true;
        return false;
    }

    public static String digitControlNib(String nib){
        char [] array=nib.toCharArray();
        int j = array.length;
        int [] intArray= new int [j];
        int i=0;
        while(i< j){
           intArray[i]= Integer.parseInt(Character.toString(array[i]));
           i++;
        }
         int x1=intArray[0]*73;
         int x2=intArray[1]*17;
         int x3=intArray[2]*89;
         int x4=intArray[3]*38;
         int x5=intArray[4]*62;
         int x6=intArray[5]*45;
         int x7=intArray[6]*53;
         int x8=intArray[7]*15;
         int x9=intArray[8]*50;
         int x10=intArray[9]*5;
         int x11=intArray[10]*49;
         int x12=intArray[11]*34;
         int x13=intArray[12]*81;
         int x14=intArray[13]*76;
         int x15=intArray[14]*27;
         int x16=intArray[15]*90;
         int x17=intArray[16]*9;
         int x18=intArray[17]*30;
         int x19=intArray[18]*3;
         double s=x1+x2+x3+x4+x5+x6+x6+x7+x8+x9+x10+x11+x12+x13+x14+x15+x16+x17+x18+x19;

         double dif= s%97;

         int nc= 98 - (int)dif;

         if(nc<10){
             return  "0" +Integer.toString(nc);
         }
         return  Integer.toString(nc);
    }
}
